package com.betty.contactstest;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
    private ListView lv_contact;
    private ArrayAdapter<String> adapter;
    List<String> contactList = new ArrayList<String>();
    Uri uri = Uri.parse("content://com.android.contacts/contacts");
    ContentResolver resolver;
    Cursor cursor;
    Button btn;

//    private SimpleCursorAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        resolver = getContentResolver();
        lv_contact = (ListView) findViewById(R.id.lv_contact);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,contactList);
//        lv_contact.setAdapter(adapter);
//        btn=(Button)findViewById(R.id.btn_contact) ;
//        readContacts();
    }

    public void query(View view) {
        readContacts();
        lv_contact.setAdapter(adapter);
    }

    public void readContacts() {
        Cursor cursor = null;
//            查询联系人数据
        cursor = MainActivity.this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, null, null, null);
        while (cursor.moveToNext()) {
//                获取联系人姓名
            String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
//                查询联系人手机号
            String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            contactList.add(displayName + "\n" + number);

        }
    }

    @Override
    protected void onDestroy() {
        if (cursor!=null)
            cursor.close();
        super.onDestroy();
    }
}